package com.springboot.middleware.middleware_redisson.server.redisson;

import com.springboot.middleware.middleware_redisson.server.dto.UserLoginDto;
import com.springboot.middleware.middleware_redisson.server.service.SysLogService;
import org.redisson.api.RTopic;
import org.redisson.api.RedissonClient;
import org.redisson.api.listener.MessageListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;

@Component
public class UserLoginSubscriber implements ApplicationRunner, Ordered {
    private static final Logger log = LoggerFactory.getLogger(UserLoginSubscriber.class);
    private static final String key = "redissonUserLoginTopicKey";

    @Autowired
    RedissonClient redissonClient;
    @Autowired
    SysLogService sysLogService;

    /**
     * Callback used to run the bean.
     *
     * @param args incoming application arguments
     * @throws Exception on error
     */
    @Override
    public void run(ApplicationArguments args) throws Exception {
        try {
            RTopic topic = redissonClient.getTopic(key);
            topic.addListener(UserLoginDto.class, (charSequence, dto) -> {
                log.info("记录用户登录成功后的轨迹-消费者-监听消费到消息: {}", dto);
                if (dto != null) {
                    sysLogService.recordLog(dto);
                }
            });
        } catch (Exception e) {
            log.error("记录用户登录成功后的轨迹-消费者-发生异常: {}", e.fillInStackTrace());
        }
    }

    /**
     * 项目启动时也跟着启动
     *
     * @return 0
     */
    @Override
    public int getOrder() {
        return 0;
    }
}
